import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import {
	http
} from '@/config/common.js'
Vue.use(Vuex)

const Store = new Vuex.Store({
	state: {
		token: uni.getStorageSync("token") || "",
		isLogin: uni.getStorageSync("isLogin") || false, // 是否登陆
		userInfo: uni.getStorageSync("userInfo") || {}, // 用户信息
	},
	getters: {
		token(state) {
			return state.token
		},
		isLogin(state) {
			return state.isLogin
		},
		userInfo(state) {
			return state.userInfo;
		}
	},
	mutations: {
		token(state, payload) {
			state.token = payload;
			uni.setStorageSync("token", payload);
		},
		// 登录态
		isLogin(state, data) {
			state.isLogin = data;
			uni.setStorageSync('isLogin', data);
		},
		// 用户信息
		userInfo(state, data) {
			state.userInfo = data;
			uni.setStorageSync("userInfo", data);
		}
	},
	actions: {
		getUserInfo(context, options) {
			http.get('getUserInfo')
				.then((res)=>{
					if(res.data.code == 0){
						context.commit('userInfo',res.data.data)
					}
				})
		},
		setUserInfo(context, options) {
			context.commit('userInfo',options)
			if(options && options.session_key){
				context.commit('token',options.session_key)
				context.commit('isLogin',true)
			} else {
				context.commit('token','')
				context.commit('isLogin',false)
			}
		}
	},
	plugins: [
		createPersistedState({
			storage: {
				getItem: key => uni.getStorageSync(key),
				setItem: (key, value) => uni.setStorageSync(key, value),
				removeItem: key => {}
			}
		})
	]
})


export default Store
